﻿using DemoWebapi01.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace DemoWebapi01.EntityTypeConfiguration
{
    /// <summary>
    /// 基础实体配置类
    /// </summary>
    /// <typeparam name="TEntity">继承自EntityBase的实体类型</typeparam>
    public class BaseEntityETConfig<TEntity> : IEntityTypeConfiguration<TEntity> where TEntity : BaseEntity
    {
        public virtual void Configure(EntityTypeBuilder<TEntity> builder)
        {
            // 配置主键
            builder.HasKey(e => e.Id);

            // 配置基础属性
            builder.Property(e => e.CreatedOn)
                .IsRequired()
                .HasComment("创建时间")
                .HasDefaultValueSql("GETDATE()");  // SQL Server 特定

            builder.Property(e => e.ModifiedOn)
                .HasComment("修改时间");

            builder.Property(e => e.LastModifiedBy)
                .HasMaxLength(100)
                .HasComment("最后修改人");

            builder.Property(e => e.IsDeleted)
                .HasDefaultValue(false)
                .HasComment("是否删除");

            builder.Property(e => e.DeletedOn)
                .HasComment("删除时间");

            builder.Property(e => e.DeletedBy)
                .HasMaxLength(100)
                .HasComment("删除人");
            builder.Property(e => e.Version)
                .IsRowVersion()
                .HasComment("版本号");

            // 添加基础索引
            builder.HasIndex(e => e.IsDeleted)
                .HasDatabaseName($"IX_{typeof(TEntity).Name}_IsDeleted");

            builder.HasIndex(e => e.CreatedOn)
                .HasDatabaseName($"IX_{typeof(TEntity).Name}_CreatedOn");

            // 添加全局查询过滤器
            builder.HasQueryFilter(e => !e.IsDeleted);

            // 调用子类的其他配置
            ConfigureOtherProperties(builder);
        }

        /// <summary>
        /// 子类可以重写此方法以添加特定的配置
        /// </summary>
        /// <param name="builder">实体类型构建器</param>
        protected virtual void ConfigureOtherProperties(EntityTypeBuilder<TEntity> builder)
        {
        }
    }
}
